package com.adee.java.commons.pool2;

import org.apache.commons.pool2.PooledObject;
import org.apache.commons.pool2.PooledObjectFactory;
import org.apache.commons.pool2.impl.DefaultPooledObject;

import java.util.UUID;


public class StringPooledObjectFactory implements PooledObjectFactory<String> {
    public StringPooledObjectFactory() {
        System.out.println("init StringPooledObjectFactory...");
    }
    // 每次调用pool.borrowObject()时都会调用该方法
    public void activateObject(PooledObject<String> pooledObject) throws Exception {
        System.out.println("activateObject...");
    }

    public void destroyObject(PooledObject<String> pooledObject) throws Exception {
        System.out.println("destroyObject...");
    }

    public PooledObject<String> makeObject() throws Exception {
        String s = UUID.randomUUID().toString();
        System.out.println("makeObject: " + s);
        return new DefaultPooledObject<String>(s);
    }

    // 每次调用pool.returnObject(obj)时都会调用该方法
    public void passivateObject(PooledObject<String> pooledObject) throws Exception {
        System.out.println("passivateObject: " + pooledObject.getObject());
    }

    public boolean validateObject(PooledObject<String> pooledObject) {
        System.out.println("validateObject: [" + pooledObject.getObject() + "]");
        return null != pooledObject.getObject();
    }
}
